package com.itheima.health.service.impl;

import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.entity.Menu;
import com.itheima.health.pojo.entity.Permission;
import com.itheima.health.pojo.entity.Role;
import com.itheima.health.pojo.entity.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User findByUsername(String username) {
        //调用DAO查询数据
        return userDao.selectByUsername(username);
    }


    @Override
    public void add(User user) {
        userDao.add(user);
    }

    /**
     * 获取角色列表
     * @param userId
     * @return
     */
    @Transactional
    @Override
    public Set<Role> getRoles(Long userId) {
        //先获取role表的字段
        Set<Role> roles=userDao.getRoles(userId);
        //在获取role相关的permission关联数据
        for (Role role : roles) {
            Set<Permission> permissions=userDao.getPermission(role.getId());
            role.setPermissions(permissions);
        }

        //再获取role关联的menu数据
        for (Role role : roles) {
            //获取一级menu
            LinkedHashSet<Menu> menus=userDao.getMenus(role.getId());
            //获取二级menu,注入一级menu中
            Iterator<Menu> iterator = menus.iterator();
            while (iterator.hasNext()) {
                Menu menu = iterator.next();
                List<Menu> children = userDao.getChild(role.getId());
                menu.setChildren(children);
            }

            //注入该角色关联的菜单数据到Role中
            role.setMenus(menus);
        }

        return roles;
    }
}
